package xkp.lesson4;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) throws InterruptedException {
/*        Sale sale1 = new Sale();
        Sale sale2 = new Sale();
        Sale sale3 = new Sale();
        sale1.start();
        sale2.start();
        sale3.start();
        sale1.join();
        sale2.join();
        sale3.join();
        System.out.println("剩余票数:"+Sale.count);*/

        Sale2 sale1 = new Sale2();
        Sale2 sale2 = new Sale2();
        Sale2 sale3 = new Sale2();
        sale1.start();
        sale2.start();
        sale3.start();
        sale1.join();
        sale2.join();
        sale3.join();
        System.out.println("剩余票数:"+Sale2.count);
    }
}


//要有一个卖票的线程类
class Sale2 extends Thread {
    //票的资源应该是共享的
    //此处模拟共享资源
    //public static Integer count = 300;
    //在java中提供了几种原子变量类型
    public static AtomicInteger count = new AtomicInteger(300);



    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            // count--
            System.out.println(count.getAndDecrement());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}




//要有一个卖票的线程类
class Sale extends Thread {
    //票的资源应该是共享的
    //此处模拟共享资源
    public static Integer count = 300;
    //加锁  ReentrantLock可重入锁  与同步关键字的做法很像
    //此处lock问题
    private static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            //此处count--非线程安全   Integer类型非线程安全
            //此处爆红是因为alibaba代码检查工具的问题
            lock.lock();
            System.out.println(count--);
            lock.unlock();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

